package com.softserve.crazymachine.communicator;

import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author radioactive.toy
 *
 */

public class Communicator implements Runnable {
		
	private static Communicator status = null;
	private ServerSocket serverSocket;
	private static ExecutorService threadPool;	
	
	private Communicator() {
		try {
			serverSocket = new ServerSocket();
		} catch (IOException e) {
		}
	}

	public static synchronized Communicator getInstance() {
		if (status == null) {
			status = new Communicator();
		}
		return status;
	}
	
	public void start() {
		new Thread(this).start();
	}
	
	public void stop() {
		try {
			serverSocket.close();
		} catch (IOException e) {;
		}
	}

	public void pause() {
		stop();
		start();
	}

	@Override
	public void run() {
		//get info from configurator
		//max threads = 100
		threadPool = Executors.newFixedThreadPool(100);
		try {
			//port = 8081
			serverSocket = new ServerSocket(8081);
			Socket clientSocket;
			while (!serverSocket.isClosed() && (!threadPool.isShutdown())) {
				clientSocket = serverSocket.accept();
				threadPool.execute(new Assignment(clientSocket));
			}
		} catch (IOException e) {
		}
	}	

}
